const Service = require('egg').Service,
  Utils = require('../utils/utils'),
  Gist = require('../utils/gist'),
  moment = require('moment'),
  _ = require('lodash');

class StatisticsService extends Service {
  async mta(param, type, option) {
    const params = _.cloneDeep(param);
    const obj = _.cloneDeep(option);
    // mat config
    const matCfg = this.config.mta;
    let url = void 0;
    const objArr = [];
    _.map(obj, v => {
      if (v) {
        objArr.push(v);
      }
    });
    switch (type) {
      case 'ctrPage':
        _.merge(params, {
          app_id: matCfg.appId,
          urls: encodeURI(_.join(objArr, ',')),
        });
        url = matCfg.ctrPageUrl;
        break;
      case 'ctrCustom':
        _.merge(params, {
          app_id: matCfg.appId,
          custom: encodeURI(_.join(objArr, ',')),
        });
        url = matCfg.ctrCustomUrl;
        break;
      default:
        break;
    }
    const sign = Utils.mtaSign(params, matCfg.secretKey);
    const curlResult = await this.ctx.curl(url, {
      data: Object.assign(params, {sign: sign}),
      dataType: 'json',
      method: 'post',
    });

    if (_.get(curlResult, 'data.code', 1) !== 0) {
      throw new Error(`mta 请求失败, ${curlResult.data.info}`);
    }
    const result = {};
    for (const prop in obj) {
      let key = obj[prop];
      key = key && key.toLowerCase();
      result[prop] = curlResult.data.data[`${key}`] || {};
    }
    return result;
  }

  async dataFunnel(data) {
    try {
      let results = void 0;
      if (data.pcode === 'QYL') {
        results = await this.app.mysql.query(Gist.qylDataFunnel(data));
      } else if (data.pcode === 'YKQJ') {
        results = await this.app.mysql.query(Gist.ykqjDataFunnel(data));
      } else {
        results = [];
      }

      return _.sortBy(results, ['日期']);
    } catch (e) {
      throw new Error('mysql 查询失败' + e.message);
    }
  }

  async mtaDataList(obj, start, end) {
    let start_date = moment(start).format('YYYYMMDD');
    const end_date = moment(end).format('YYYYMMDD');
    const result = [];
    while (!moment(start_date).isAfter(end_date)) {
      const temp = {};
      temp.date = moment(start_date).format('YYYY-MM-DD');
      for (const key in obj) {
        if (obj[key][start_date]) {
          temp[key] = obj[key][start_date];
          if (!temp[key].pv) {
            temp[key].pv = 0;
          }
          if (!temp[key].uv) {
            temp[key].uv = 0;
          }
        } else {
          temp[key] = {pv: 0, uv: 0};
        }
      }
      result.push(temp);
      start_date = moment(start_date).add(1, 'days').format('YYYYMMDD');
    }
    return result;
  }
}

module.exports = StatisticsService;
